{% extends "layout/manage.html" %}
{% load static %}

{% block title %}
    问题
{% endblock %}

{% block css %}
    <link rel="stylesheet" href="{% static "plugin/editor-md/css/editormd.min.css" %}">
    <link rel="stylesheet"
          href="{% static "plugin/bootstrap-datepicker-master/bootstrap-datepicker-master/dist/css/bootstrap-datepicker.min.css" %}">
    <link rel="stylesheet" href="{% static "plugin/bootstrap-select/css/bootstrap-select.min.css" %}">
    <style>

        .comment-area .item {
            margin-top: 20px;
        }

        .comment-area .left-avatar {
            float: left;
            margin-right: 10px;
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #304659;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .comment-area .right-info {
            padding-left: 35px;
        }

        .comment-area .right-info .desc .msg {
            display: inline-block;
            padding-right: 20px;
            color: #8c8c8c;
        }

        .comment-area .child {
            padding-left: 55px;
        }

        .comment-area .error-msg {
            position: absolute;
            color: red;
        }

        .comment-area .reply-user {
            display: inline-block;
            background-color: #ddd;
            color: black;
            padding: 6px 8px;
            margin-left: 20px;
            border-radius: 8px;
            cursor: pointer;
        }

        .filter-area .error-msg {
            position: absolute;
            color: red;
        }

        .editormd-fullscreen {
            z-index: 1001;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="container-fluid clearfix" style="padding: 20px 0;">
        <div class="col-sm-7">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-search" aria-hidden="true"></i> 更新问题
                </div>
                <div class="panel-body filter-area">
                    <form id="addForm" class="form-horizontal">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="{{ form.issues_type.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.issues_type.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.issues_type }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.subject.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.subject.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.subject }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.module.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.module.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.module }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.desc.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.desc.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div id="editor">
                                        {{ form.desc }}
                                    </div>

                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>

                        <div class="form-group clearfix">

                            <div class="col-md-6 pd-0">
                                <label for="{{ form.status.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.status.label }}</label>
                                <div class="col-md-8 clearfix">
                                    <div>
                                        {{ form.status }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                            <div class="col-md-6 pd-0">
                                <label for=" {{ form.priority.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.priority.label }}</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.priority }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">指派给</label>
                                <div class="col-md-8">
                                    {{ form.assign }}
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">关注者</label>
                                <div class="col-md-8">

                                    {{ form.attention }}

                                    <div class="error-msg"></div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">开始时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.start_date }}
                                    </div>
                                    <span class="error-msg"></span>

                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">截止时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.end_date }}
                                    </div>
                                    <span class="error-msg"></span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">模式</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.mode }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label"> 父问题</label>
                                <div class="col-md-8">

                                    {{ form.parent }}

                                    <div class="error-msg"></div>
                                </div>
                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
        <div class="col-sm-5">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-search" aria-hidden="true"></i> 操作记录
                </div>
                <div class="panel-body comment-area">
                    <div class="comment-list">

                    </div>

                    <hr/>
                    <div class="comment-text" id="commentText">
                        <div class="form-group">
                            <textarea id="content" rows="6" class="form-control"
                                      placeholder="请输入要回复的内容"></textarea>
                            <span class="error-msg"></span>
                        </div>
                        <input class="btn btn-primary" type="button" id="btnSubmit" value="提 交">
                        <div class="reply-user hide" id="replyUser">
                            回复 <span></span>
                            <i class="fa fa-times-circle" aria-hidden="true" style="color: #9d9d9d;"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="hide" id="recordTemplate">
        <div class="item clearfix">
            <div class="left-avatar"></div>
            <div class="right-info">
                <pre></pre>
                <div class="desc">
                    <div class="msg">
                        <i class="fa fa-bullhorn" aria-hidden="true"></i>
                        <span class="type"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-user-o" aria-hidden="true"></i>
                        <span class="user"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-clock-o" aria-hidden="true"></i>
                        <span class="date"></span>
                    </div>

                    <a href="#content" class="reply">
                        <i class="fa fa-commenting-o" aria-hidden="true"></i> 回复
                    </a>

                </div>
            </div>
            <div class="child">

            </div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script src="{% static "plugin/editor-md/editormd.min.js" %}"></script>
    <script src="{% static "plugin/bootstrap-datepicker-master/bootstrap-datepicker-master/dist/js/bootstrap-datepicker.min.js" %}"></script>
    <script src="{% static "plugin/bootstrap-datepicker-master/bootstrap-datepicker-master/dist/locales/bootstrap-datepicker.zh-CN.min.js" %}"></script>
    <script src="{% static "plugin/bootstrap-select/js/bootstrap-select.min.js" %}"></script>
    <script src="{% static "plugin/bootstrap-select/js/i18n/defaults-zh_CN.min.js" %}"></script>
    <script>
        var WIKI_UPLOAD_URL = "{% url 'wiki_upload' project_id=request.tartec.project.id  %}"
        var ISSUES_RECORD_URL = "{% url 'issues_record' project_id=request.tartec.project.id issues_id=issues_object.id %}"
        var CHANGE_MESSAGE_URL = "{% url 'issues_change' project_id=request.tartec.project.id issues_id=issues_object.id %}"
        var EDITOR

        $(() => {
            initBootStrap_Datepicker()
            initEditorMd()
            initIssuesRecord()
            Record()
            UnRecord()
            bindOnSubmit()
            bindChangeIssues()
        })

        function initEditorMd() {
            EDITOR = editormd("editor", {
                // 输入框中的默认提示
                placeholder: "请输入内容",
                // 默认行高
                height: 300,
                // 需要设置配置文件的路径
                path: "{% static 'plugin/editor-md/lib/' %}",
                // 设置是否能上传图片
                imageUpload: true,
                // 设置可以上传图片的文件后缀
                imageFormats: ["jpg", 'jpeg', 'png', 'gif'],
                //  上传图片的地址
                imageUploadURL: WIKI_UPLOAD_URL,
                toolbarAutoFixed: false, // 工具栏是否固定在页面上
                toolbarIcons: function () { // 自定义markdown 工具栏
                    return ["bold", "hr", "del", "italic", "quote", "|", "image", "preview", "watch", "fullscreen", "||", "save"]
                },
                toolbarCustomIcons: { // 自定义markdown 以什么方式呈现
                    save: "<input type='button' value='保 存' class='btn btn-success btn-sm' onclick='saveDesc();' />"
                },
                onload: function () {
                    this.previewing() // 以预览的形式默认呈现
                }
            })
        }

        function initBootStrap_Datepicker() {
            $("#id_start_date,#id_end_date").datepicker({
                format: "yyyy-mm-dd", // 数据格式
                startDate: "0", // 从哪一天开始选择，0 表示今天
                language: "zh-CN", // 语言，中文需要导包
                autoclose: true, // 选择完毕，是否自动关闭
            })
        }

        // 初始化评论的数据
        function initIssuesRecord() {
            $.ajax({
                url: ISSUES_RECORD_URL,
                type: "GET",
                dataType: "JSON",
                success: function (res) {
                    console.log(res)
                    if (res.status) {
                        $.each(res.data, function (index, item) {
                            createRecordNode(item)
                        })
                    } else {
                        console.log(res.error)
                    }
                }
            })
        }

        // 创建操作节点
        function createRecordNode(nodeDict) {
            var $item = $("#recordTemplate").find('.item').clone();
            $item.find('.left-avatar').html(nodeDict.user[0].toUpperCase());
            $item.find('pre').html(nodeDict.action);
            $item.find('.user').html(nodeDict.user);
            $item.find('.type').html(nodeDict.status);
            $item.find('.date').html(nodeDict.create_date);
            $item.attr({id: nodeDict.id, username: nodeDict.user});

            if (nodeDict.parent) {
                // 挂在谁下
                $('#' + nodeDict.parent).children('.child').append($item);
            } else {
                // 根下
                $('.comment-list').append($item);
            }
        }

        // 回复按钮
        function Record() {
            $('.comment-list').on('click', '.reply', function () {
                let $item = $(this).parent().parent().parent();
                let id = $item.attr('id');
                let username = $item.attr('username');
                $('#replyUser').removeClass('hide').attr('parent-id', id).children('span').text(username);
            })
        }

        // 取消回复
        function UnRecord() {
            $("#replyUser").click(function () {
                $("#replyUser").addClass("hide").removeAttr("parent-id").children("span").empty()
            })
        }

        // 提交回复信息
        function bindOnSubmit() {
            // 清空报错信息
            $("#content .error-msg").empty()
            $("#btnSubmit").click(function () {
                let data = {
                    parent: $("#replyUser").attr("parent-id"),
                    action: $("#content").val()
                }
                $.ajax({
                    url: ISSUES_RECORD_URL,
                    type: "POST",
                    dataType: "JSON",
                    data: data,
                    success: function (res) {
                        if (res.status) {
                            // 动态添加到页面回复的消息
                            createRecordNode(res.data)
                            // 清空回复消息，以及回复人
                            $("#content").val("")
                            UnRecord()
                        } else {
                            $.each(res.error, function (k, v) {
                                $("#content").next(".error-msg").text(v[0])
                            })
                        }
                    }
                })
            })
        }

        // 绑定事件
        function bindChangeIssues() {
            $('#addForm').find('.form-control').change(function () {
                let change_message = {
                    name: $(this).attr("name"),
                    value: $(this).val()
                }
                console.log(change_message)
                bindSaveForm(change_message)
            })
        }

        // 改变markdown 值
        function saveDesc() {
            let change_message = {
                name: "desc",
                value: EDITOR.getValue()
            }
            bindSaveForm(change_message)
        }

        // 保存改变表单的值
        function bindSaveForm(changeDict) {
            $("#id_" + changeDict.name).parent().next(".error-msg").text("")
            $.ajax({
                url: CHANGE_MESSAGE_URL,
                header: {
                    "Content-Type": "application/json;charset=utf-8",
                },
                type: "POST",
                dataType: "JSON",
                data: JSON.stringify(changeDict),
                success: function (res) {
                    if (res.status) {
                        createRecordNode(res.data)
                    } else {
                        $("#id_" + changeDict.name).parent().next(".error-msg").text(res.error)
                    }
                }
            })
        }
    </script>
{% endblock %}